package com.imooc.course.system.controller.admin;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/admin/kaptcha")
public class KaptchaController {

    private static final Logger log = LoggerFactory.getLogger(KaptchaController.class);
    public static final String BUSINESS_NAME = "kaptcha";

    @Resource(name = "defaultKaptcha")
    DefaultKaptcha defaultKaptcha;

    @Resource(name = "adminKaptcha")
    DefaultKaptcha adminKaptcha;

    @Resource
    public RedisTemplate redisTemplate;

    @GetMapping("/image-code/{imageCodeToken}")
    public void imageCode(
            @PathVariable(value = "imageCodeToken") String imageCodeToken
            , HttpServletRequest request
            , HttpServletResponse httpServletResponse) throws IOException
    {
        ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
        try {
            // 生成验证码字符串
            String createText = defaultKaptcha.createText();

            // 将生成的验证码放入会话缓存中，后续验证的时候用到
            //request.getSession().setAttribute(imageCodeToken, createText);

            //使用第三方redis作为共享session，将生成的验证码放入缓存中，后续验证的时候用到
            redisTemplate.opsForValue().set(imageCodeToken, createText, 300, TimeUnit.SECONDS);


            // 使用验证码字符串生成验证码图片
            BufferedImage challenge = defaultKaptcha.createImage(createText);
            ImageIO.write(challenge, "jpg", jpegOutputStream);
        } catch (IllegalArgumentException e) {
            httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        //日志输出查看imageCodeToken设置进session是否生效
        String kaptcha = (String)redisTemplate.opsForValue().get(imageCodeToken);
        log.info("imageCodeToken 已存入 共享Session ==> KEY = {}，VALUE = {} ", imageCodeToken, kaptcha);

        // 定义response输出类型为image/jpeg类型，使用response输出流输出图片的byte数组
        byte[] captchaChallengeAsJpeg = jpegOutputStream.toByteArray();
        httpServletResponse.setHeader("Cache-Control", "no-store");
        httpServletResponse.setHeader("Pragma", "no-cache");
        httpServletResponse.setDateHeader("Expires", 0);
        httpServletResponse.setContentType("image/jpeg");
        ServletOutputStream responseOutputStream = httpServletResponse.getOutputStream();
        responseOutputStream.write(captchaChallengeAsJpeg);
        responseOutputStream.flush();
        responseOutputStream.close();
    }

    /**
     * 后台工作人员使用辨识度更高，更清晰的验证码图片
     * @param imageCodeToken
     * @param request
     * @param httpServletResponse
     * @throws IOException
     */
    @GetMapping("/image-simple-code/{imageCodeToken}")
    public void imageSimpleCode(
            @PathVariable(value = "imageCodeToken") String imageCodeToken
            , HttpServletRequest request
            , HttpServletResponse httpServletResponse) throws IOException
    {
        ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
        try {
            // 生成验证码字符串
            String createText = adminKaptcha.createText();

            // 将生成的验证码放入会话缓存中，后续验证的时候用到
            //request.getSession().setAttribute(imageCodeToken, createText);

            //使用第三方redis作为共享session，将生成的验证码放入缓存中，后续验证的时候用到
            redisTemplate.opsForValue().set(imageCodeToken, createText, 300, TimeUnit.SECONDS);


            // 使用验证码字符串生成验证码图片
            BufferedImage challenge = adminKaptcha.createImage(createText);
            ImageIO.write(challenge, "jpg", jpegOutputStream);
        } catch (IllegalArgumentException e) {
            httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        //日志输出查看imageCodeToken设置进session是否生效
        String kaptcha = (String)redisTemplate.opsForValue().get(imageCodeToken);
        log.info("imageCodeToken 已存入 共享Session ==> KEY = {}，VALUE = {} ", imageCodeToken, kaptcha);

        // 定义response输出类型为image/jpeg类型，使用response输出流输出图片的byte数组
        byte[] captchaChallengeAsJpeg = jpegOutputStream.toByteArray();
        httpServletResponse.setHeader("Cache-Control", "no-store");
        httpServletResponse.setHeader("Pragma", "no-cache");
        httpServletResponse.setDateHeader("Expires", 0);
        httpServletResponse.setContentType("image/jpeg");
        ServletOutputStream responseOutputStream = httpServletResponse.getOutputStream();
        responseOutputStream.write(captchaChallengeAsJpeg);
        responseOutputStream.flush();
        responseOutputStream.close();
    }
}

